<template>
  <div class="sys-role">

    <AppMainHeader>
      <el-row>
        <el-col :span="22">
          <SysRoleQueryForm @query="handleQuery"/>
        </el-col>
        <el-col :span="2" class="align-right">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['sys:role:add']">
            新增
          </el-button>
        </el-col>
      </el-row>
    </AppMainHeader>

    <AppMainContent>
      <SysRoleTable
        v-loading="loading"
        :data="roleList"
        @row-update="handleUpdate"
        @row-layer="handleLayer"
        @row-delete="handleDelete"
      />

<!--      <el-table v-loading="loading" :data="roleList">-->
<!--        <el-table-column-->
<!--          label="序号"-->
<!--          align="center"-->
<!--          prop="rowNumber"-->
<!--          width="100"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="角色名称"-->
<!--          align="left"-->
<!--          prop="name"-->
<!--          :show-overflow-tooltip="true"-->
<!--          min-width="30%"-->
<!--        />-->
<!--        &lt;!&ndash;<el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true"/>&ndash;&gt;-->
<!--        <el-table-column-->
<!--          label="是否禁用"-->
<!--          align="center"-->
<!--          prop="isDisabled"-->
<!--          :formatter="isDisabledFormat"-->
<!--          min-width="10%"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="创建时间"-->
<!--          align="center"-->
<!--          prop="createTime"-->
<!--          min-width="30%"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column-->
<!--          label="操作"-->
<!--          align="center"-->
<!--          class-name="small-padding"-->
<!--          min-width="30%"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleUpdate(scope.row)"-->
<!--              v-hasPermi="['system:role:edit']"-->
<!--            >-->
<!--              修改-->
<!--            </el-button>-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleLayer(scope.row)"-->
<!--              v-hasPermi="['system:role:edit']"-->
<!--            >-->
<!--              地图图层-->
<!--            </el-button>-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleDelete(scope.row)"-->
<!--              v-hasPermi="['system:role:remove']"-->
<!--            >-->
<!--              删除-->
<!--            </el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->

      <Pagination
        v-show="total > 0"
        :total="total"
        :current.sync="queryParams.pageNum"
        :size.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </AppMainContent>



    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="530px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符"/>
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            @keydown.native="channelInputLimit"
            controls-position="right"
            :min="0"
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.isDisabled">
            <el-radio
              v-for="dict in isDisabledOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >
              {{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">
            展开/折叠
          </el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll">
            全选/全不选
          </el-checkbox>
          <el-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect"
          >
            父子联动
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改地图图层"
      :visible.sync="mapOpen"
      width="530px"
      append-to-body
    >
      <el-form :model="mapForm" :rules="mapRules" label-width="85px">
        <el-form-item label="地图图层">
          <el-tree
            class="tree-border"
            :data="layerOptions"
            show-checkbox
            ref="mapTree"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapCancel">取 消</el-button>
        <el-button type="primary" @click="mapSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  exportRole,
  dataScope,
  changeRoleStatus,
  treeLayer,
  modifyRoleLayer
} from '@/api/system/role'
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect
} from '@/api/system/menu'

import SysRoleQueryForm from '@/views/system/components/sys-role-query-form'
import SysRoleTable from '@/views/system/components/sys-role-table'

export default {
  name: 'SysRole',
  components: { SysRoleQueryForm, SysRoleTable },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      //openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      isDisabledOptions: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: 1,
          label: '全部数据权限'
        },
        {
          value: 2,
          label: '公司数据权限'
        },
        {
          value: 3,
          label: '仅个人数据权限'
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        currPage: 1,
        pageSize: 10,
        name: undefined,
        isDisabled: undefined,
        orderColumn: undefined,
        orderDirection: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { max: 15, message: '长度不超过15个字符', trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' },
          { max: 50, message: '长度不超过50个字符', trigger: 'blur' }
        ],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' }
        ]
      },
      mapOpen: false,
      mapForm: {
        roleId: null,
        layerIds: []
      },
      mapRules: {},
      layerOptions: []
    }
  },
  created() {
    // this.getList()
    // this.getDicts('sys_normal_disable').then((response) => {
    //   this.isDisabledOptions = response.data
    // })
  },
  methods: {
    /** 橘色状态格式化 **/
    isDisabledFormat(row, column) {
      return this.selectDictLabel(this.isDisabledOptions, row.isDisabled)
    },
    channelInputLimit(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.') {
        e.returnValue = false
        return false
      }
      return true
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole(this.queryParams).then((response) => {
        this.roleList = response.data
        this.total = response.page.total
        this.loading = false
      })
    },
    /** 新增时查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有图层节点数据
    getLayerAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.mapTree.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.mapTree.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect({ id: roleId }).then((response) => {
        this.menuOptions = response.data.menus
        return response
      })
    },

    // 地图图层设置
    handleLayer(row) {
      let vm = this
      vm.mapOpen = true
      vm.mapForm.roleId = row.id
      vm.$nextTick(() => {
        treeLayer({ id: row.id }).then((response) => {
          vm.layerOptions = response.data.layers
          vm.$refs.mapTree.setCheckedKeys(response.data.checkedKeys)
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    mapCancel() {
      this.mapOpen = false
      this.$refs.mapTree.setCheckedKeys([])
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      ;(this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          id: undefined,
          name: undefined,
          roleKey: undefined,
          // roleSort: 0,
          isDisabled: 0,
          menuIds: [],
          menuCheckStrictly: true,
          remark: undefined
        })
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand() {
      let treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.form.menuCheckStrictly = value ? true : false
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getMenuTreeselect()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const roleId = row.id || this.ids
      const roleMenu = this.getRoleMenuTreeselect(roleId)
      getRole({ id: roleId }).then((response) => {
        this.form = response.data
        this.open = true
        this.$nextTick(() => {
          roleMenu.then((res) => {
            this.$refs.menu.setCheckedKeys(res.data.checkedKeys)
          })
        })
        this.title = '修改角色'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.menuCheckStrictly = this.form.menuCheckStrictly ? 1 : 0
          if (this.form.id != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            updateRole(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            addRole(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 图层提交
    mapSubmitForm() {
      let vm = this
      vm.mapForm.layerIds = vm.getLayerAllCheckedKeys()
      modifyRoleLayer(this.mapForm).then((response) => {
        vm.mapOpen = false
        this.$refs.mapTree.setCheckedKeys([])
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleId = row.id
      this.$confirm(
        '是否确认删除角色名称为"' + row.name + '"的数据项?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delRole({ id: roleId })
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    }
  }
}
</script>
